package fm.dongman.animefm.view.fragment

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.os.Bundle
import android.support.v4.view.ViewPager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import com.bumptech.glide.Glide
import fm.dongman.animefm.R
import fm.dongman.animefm.contractlib.IModel
import fm.dongman.animefm.contractlib.contract.ComicCourierContract
import fm.dongman.animefm.view.activity.SingleActivity
import fm.dongman.animefm.view.adapter.ComicCourierPagerAdapter
import fm.dongman.animefm.view.transform.GlideRoundTransform
import fm.dongman.animefm.view.util.ActivityHelper
import fm.dongman.animefm.view.util.SystemHelper
import fm.dongman.animefm.view.util.ToastHelper
import fm.dongman.animefm.view.widget.MultiStateLayout
import fm.dongman.modellib.StaticArea.Injection
import fm.dongman.modellib.model.ComicModel
import fm.dongman.modellib.source.ComicCourierRepository
import fm.dongman.presenterlib.presenter.ComicCourierPresenter
import kotlinx.android.synthetic.main.fragment_comic_courier.*
import kotlinx.android.synthetic.main.item_comic_courier.view.*
import org.jetbrains.anko.onClick

/**
 * 新番速递页面
 * Created by shize on 2017/10/23.
 */
class ComicCourierFragment : BaseFragment(), ComicCourierContract.IComicCourierView {
    private lateinit var mPresenter: ComicCourierContract.IComicCourierPresenter
    private var mRecyclers: ArrayList<RecyclerView> = ArrayList() // 新番列表
    private lateinit var mQuarters: List<Map<String, String>> // 季度

    override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View {
        val fragment = inflater!!.inflate(R.layout.fragment_comic_courier, container, false)
        ComicCourierPresenter(this, Injection.provideComicCourierRepository())
        return fragment
    }

    override fun initData() {
        onStateChanged(MultiStateLayout.LOADING)
        mPresenter.startLoad()
    }

    override fun bindData() {
        bindToolbar()
        bindPage()
    }

    /**
     * 绑定 toolbar
     */
    private fun bindToolbar() {
        mCourierToolbar.setPadding(0, SystemHelper.getStatusBarHeight(activity), 0, 0)
        mCourierToolbar.setNavigationOnClickListener {
            ActivityHelper.backActivity(activity)
        }
    }

    /**
     * 绑定 pages
     */
    private fun bindPage() {
        mCourierPager.offscreenPageLimit = 2
        mCourierPager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrollStateChanged(state: Int) {}

            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {}

            override fun onPageSelected(position: Int) {
                onStateChanged(MultiStateLayout.LOADING)
                getQuarterComic(position)
            }
        })
    }

    /**
     * 获取季度番剧列表
     * @param position 位置
     */
    private fun getQuarterComic(position: Int) {
        mPresenter.quarterComic(mQuarters[position].keys.first(), ComicCourierRepository.ORDER_NEW)
    }

    override fun setPresenter(presenter: ComicCourierContract.IComicCourierPresenter) {
        mPresenter = presenter
    }

    override fun isActive(): Boolean {
        return isAdded
    }

    override fun getViewContext(): Context {
        return activity
    }

    override fun showNoNetwork() {
        onStateChanged(MultiStateLayout.NET_ERROR)
    }

    override fun showRefreshFailed() {
        ToastHelper.getInstance(activity).showError("新番速递页面加载失败！")
    }

    override fun showQuarters(quarters: List<Map<String, String>>) {
        // 先清空，再重新赋值
        mRecyclers.clear()
        mCourierTab.removeAllTabs()
        mQuarters = quarters
        // 重新赋值
        quarters.forEach {
            mRecyclers.add(RecyclerView(activity))
            // 设置 tab
            mCourierTab.addTab(mCourierTab.newTab().setText(it.values.first()))
        }
        mCourierPager.adapter = ComicCourierPagerAdapter(activity, quarters.map { it.values.first() }, mRecyclers)
        mCourierTab.setupWithViewPager(mCourierPager)
        // 加载首个季度列表
        getQuarterComic(0)
    }

    override fun showComicList(comics: List<IModel.IComicModel>, quarter: String) {
        onStateChanged(MultiStateLayout.SUCCESS)
        mRecyclers[mQuarters.map { it.keys.first() }.indexOf(quarter)].adapter = ComicCourierRecyclerAdapter(activity, comics)
    }

    /**
     * 改变数据状态
     */
    private fun onStateChanged(state: Int) {
        mCourierMultiStateLayout.changeState(state)
    }

    companion object {
        fun getInstance(): ComicCourierFragment {
            return ComicCourierFragment()
        }
    }

    /**
     * 新番速递列表适配器
     */
    class ComicCourierRecyclerAdapter constructor(private val mContext: Context,
                                                  private val mData: List<IModel.IComicModel>)
        : RecyclerView.Adapter<ComicCourierViewHolder>() {

        override fun getItemCount(): Int = mData.size

        override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ComicCourierViewHolder =
                ComicCourierViewHolder(LayoutInflater.from(mContext).inflate(R.layout.item_comic_courier, null))

        @SuppressLint("SetTextI18n")
        override fun onBindViewHolder(holder: ComicCourierViewHolder?, position: Int) {
            val comic = mData[position] as ComicModel
            holder!!.mComicTitle.text = comic.title
            Glide.with(mContext).load(comic.imgUrl)
                    .centerCrop()
                    .transform(GlideRoundTransform(mContext, 4))
                    .into(holder.mComicImage)
            holder.mComicProgress.text = "更新到第${comic.episodes}集"
            holder.mComicTime.text = comic.insertTime
            holder.mComicSubTitle.text = comic.summary
            holder.itemView.onClick {
                if (comic.id != null) {
                    ActivityHelper.startActivity(mContext as Activity, SingleActivity::class.java, mapOf(
                            Pair(SingleActivity.EXTRA_NAME, SingleActivity.INTENT_EXTRA_ANIME_INFO),
                            Pair(SingleActivity.BUNDLE_EXTRA_KEY_ID, comic.id)), false)
                }
            }
        }
    }

    /**
     * 新番速递列表适配器 ViewHolder
     */
    class ComicCourierViewHolder constructor(itemView: View) : RecyclerView.ViewHolder(itemView) {
        var mComicImage: ImageView = itemView.mComicImage // 图片
        var mComicTitle: TextView = itemView.mComicTitle // 名称
        var mComicProgress: TextView = itemView.mComicProgress // 进度
        var mComicTime: TextView = itemView.mComicTime // 间隔时间
        var mComicSubTitle: TextView = itemView.mComicSubTitle // 简介
    }
}